<template>
    <div>
        <span v-html="displayedText"></span>
        <!--        <span v-if="cursorVisible" class="cursor">|</span>-->
    </div>
</template>
<script>
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'
export default {
    props: {
        text: {
            type: String,
            required: true
        },
        speed: {
            type: Number,
            default: 1000 // 每个字符显示的速度，默认100ms
        },
        isStop:{
            type: Boolean,
            default: false // 是否显示光标
        },
        cursor: {
            type: Boolean,
            default: true // 是否显示光标
        }
    },
    data() {
        return {
            displayedText: '',
            cursorVisible: true
        };
    },
    mounted() {
        this.typeText();
        if (this.cursor) {
            this.blinkCursor();
        }
    },

    methods: {
        markdownText(rendContent){
            let md= new MarkdownIt({
                html: true,
                linkify: true,
                typographer: true,
                breaks: true,        // Convert '\n' in paragraphs into <br>
                highlight: function (str, lang) {
                    if (lang && hljs.getLanguage(lang)) {
                        try {
                            return `<pre><code class="language-${lang} hljs">` +
                                hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                                '</code></pre>';
                        } catch (__) {}
                    }
                    return '<pre><code class="language-none hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
                }
            })
            return md.render();
        },
        async typeText() {
            for (let i = 0; i < this.text.length; i++) {
                this.displayedText += this.text[i];
                if (this.isStop) {
                    break;
                }
                await this.sleep(this.speed);
            }
            this.$emit('loadOver', {'status': true, 'copytext': this.displayedText});
        },
        sleep(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        },
        blinkCursor() {
            setInterval(() => {
                this.cursorVisible = !this.cursorVisible;
            }, 50);
        }
    }
};
</script>
<style scoped>
.cursor {
    display: inline-block;
    width: 1px;
    background-color: black;
}
</style>
